// pages/order/order.js
const app = getApp();
let wxCharts = require('../../utils/wxcharts.js');
import request from '../../utils/http.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {

    visible: false,
    isClick: false, //确认支付是否点击
    shareble: false, //分享弹框
    sharebleIndex: 1, //1 为自己众筹分享 2 让别人发起分享
    hiddenSharePaper: true, //分享海报的弹框是否隐藏
    fenXiangDaBeiJingTu2: '', //生成二维码的背景图 发起
    fenXiangXiaoBeiJingTu2: '', //分享链接封面图 发起
    touXiangUrl: 'https://insurancecard.oneplusyang.com/202211211518277613028017ac47bca829ceba588a3c5a.png',
    niCheng: '',

    width: 0,
    payMoneyToMe: [],


    chanPinMingCheng: '', //产品名称
    tuPianUrl: '', //产品封面
    shiJiJiaGe: 0, //实际销售价格
    chanPinShuoMing: '', //说明
    neiRong: '', //产品详情

    jinE: 0,
    jinETemp: '',
    select_index: 1, //众筹金额
    personId: 0,
    zhongChouOrderFormId: 0, //众筹id
    zhongXinChanPinId: 0, //产品id
    chanPinLeiXing:0,//1普通产品，2 服务包
    yiChouJinEStr: 0, //已筹金额
    targetMoneyStr: 0, //需要筹集金额
    wanChengBiLv: 0, //完成比率
    zhiChiRenShu: 0, //支持人数
    chanPinDanJiaStr: 0, //产品单价
    fenShu: 0, //份数
    yiFaSongChanPinShuLiang: 0, //已发送产品的数量
    zhuangTai: '', //1众筹中，2已经结束
    myTouXiangUrl: "", //自己的头像
    myName: '', //自己的昵称
    // personList:[{"personTouXiangUrl":"https://zsdlqn.zijiapuzi.com/1694749397767.9873","personName":"人参养生酒"}],//已助力用户list
    personList: [], //已助力用户list
    personListLength:0,
    shareFlag: false, //true 通过分享进入
    IsLogin: false, //判断是否登录
    login_dianPuId: 0, //已登录店铺ID，用于判断需不需要重新登录.
    myPersonId: '', //发起人的persionId
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenHeight: res.screenHeight,
          width: res.screenWidth
        })
      }
    })

    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    })

    that.setData({
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      zhongChouOrderFormId: options.zhongChouOrderFormId,
      shareFlag: options.shareFlag,
      login_dianPuId: (wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID),
      dianPuId: (options.dianPuId == '' || options.dianPuId == undefined) ? ((wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID)) : options.dianPuId,
      tjr_id: (options.tjr_id == '' || options.tjr_id == undefined) ? wx.getStorageSync(app.globalData.TJR_ID) : options.tjr_id,
      shareFlag: (options.tjr_id == '' || options.tjr_id == undefined) ? false : true,
    })


    if (options.scene) { //海报扫码
      let scene = decodeURIComponent(options.scene);
      that.setData({
        dianPuId: scene.split("_")[0],
        tjr_id: scene.split("_")[1],
        zhongChouOrderFormId: scene.split("_")[2],
        shareFlag: true
      })
    }

    wx.setStorageSync(app.globalData.SHOPID, that.data.dianPuId)
    wx.setStorageSync(app.globalData.TJR_ID, that.data.tjr_id)
    if (that.data.login_dianPuId == that.data.dianPuId && that.data.dianPuId > 0) {
      that.setData({
        IsLogin: wx.getStorageSync(app.globalData.LOGINSTATUS) == true ? true : false,
      })
    } else {
      that.setData({
        IsLogin: false,
      })
    }

    wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)


    //初始化支付金额
    that.setData({
      jinE: 990,
      select_index: 1,
      jinETemp: 9.9
    })
    this.getoneZc()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.getAllOrderList();
    this.getoneZc()
  },




  //获取一个众筹
  getoneZc: function () {
    var that = this
    let data = {
      zhongChouOrderFormId: that.data.zhongChouOrderFormId,
    }
    request.get('zhongChou/getOneZhongChou', data, res => {
      // console.log("众筹详情:" + JSON.stringify(res.data))
      that.setData({
        chanPinLeiXing:res.data.chanPinLeiXing,
        zhongXinChanPinId: res.data.zhongXinChanPinId,
        yiChouJinEStr: res.data.yiChouJinEStr,
        targetMoneyStr: res.data.targetMoneyStr,
        wanChengBiLv: res.data.wanChengBiLv,
        zhiChiRenShu: res.data.zhiChiRenShu,
        chanPinDanJiaStr: res.data.chanPinDanJiaStr,
        fenShu: res.data.fenShu,
        yiFaSongChanPinShuLiang: res.data.yiFaSongChanPinShuLiang,
        zhuangTai: res.data.zhuangTai,
        isClick:res.data.zhuangTai==1?false:true,
        myTouXiangUrl: res.data.myTouXiangUrl,
        myName: res.data.myName,
        personList: res.data.personList,
        personListLength:res.data.personList.length,
        myPersonId:res.data.myPersonId
      })

       if(res.data.chanPinLeiXing==2){
        that.getFWBDetail(res.data.zhongXinChanPinId)
       }else{
        that.getProductDetail(res.data.zhongXinChanPinId)
       }


      wx.hideLoading();
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },

  //获取产品详情
  getProductDetail: function (id) {
    var that = this
    wx.showLoading({
      title: '产品加载中...',
      mask: true
    })
    let data = {
      productId: id,
      dianPuId: that.data.dianPuId,
    }
    console.log(data)
    request.get('product/productDetailInfo', data, res => {
      // console.log("产品详情:" + JSON.stringify(res.data))
      that.setData({
        chanPinMingCheng: res.data.chanPinMingCheng, //产品名称
        tuPianUrl: res.data.tuPianUrl, //封面图

        shiPinUrl: res.data.shiPinUrl, //产品视频
        chanPinImageList: res.data.chanPinImageList, //产品轮播图
        chanPinShuoMing: res.data.chanPinShuoMing,
        swiperListLength: res.data.shiPinUrl == '' ? res.data.chanPinImageList.length : parseInt(res.data.chanPinImageList.length + 1), //轮播长度
      })

      var html = res.data.neiRong.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
      var htmlS = html.replace(/style=""/g, '')

      that.setData({
        neiRong: htmlS
      })

      wx.hideLoading();
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },


  //获取服务包详情
  getFWBDetail: function (id) {
    var that = this
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let data = {
      fuWuBaoChanPinIdId: id,
    }
    request.get('fuWuBao/fuWuBaoDetailInfo', data, res => {

      // console.log("服务包:" + res.data.huiYuanJiaGe)
      that.setData({
        chanPinMingCheng: res.data.mingCheng,
        tuPianUrl: res.data.productBeiJingTuUrl,
        shiPinUrl: res.data.shiPinUrl,
        chanPinImageList: res.data.chanPinImageList,
        chanPinShuoMing: res.data.productComment,
        swiperListLength: res.data.shiPinUrl == '' ? res.data.chanPinImageList.length : parseInt(res.data.chanPinImageList.length + 1), //轮播长度 
      })

      var html = res.data.productInfo.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
      var htmlS = html.replace(/style=""/g, '')

      that.setData({
        neiRong: htmlS
      })

      wx.hideLoading();
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },
  

  // 弹出分享选项
  pickShareAction() {
    console.log("打开")
    this.setData({
      shareble: true,
    })
  },
  //关闭分享弹窗
  pickShareActionX() {
    console.log("关闭")
    this.setData({
      shareble: false,
    })
  },
  //开始支付弹窗
  pickToZhifu() {
    // console.log("支付弹窗")
    if (this.data.IsLogin) { //已登录，可以支付
      this.setData({
        visible: true,
      })
    } else { //未登录，先登录
      wx.hideLoading();
      wx.showToast({
        title: '请登录后进行助力!!!', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })


    }
  },
  //  确认支付
  payAction: function () {
    var that = this
    let data = {
      openId: wx.getStorageSync(app.globalData.OPENID),
      zhongChouOrderFormId: that.data.zhongChouOrderFormId,
      zhiFuJinE: that.data.jinE,
    }

    request.get('zhongChou/fuKuan', data, res => {
      // console.log("支付:" + JSON.stringify(res.data))
      wx.hideLoading()
      if (res.data.status == 1) {
        wx.requestPayment({
          timeStamp: res.data.map.timeStamp,
          nonceStr: res.data.map.nonce_str,
          package: 'prepay_id=' + res.data.map.prepay_id,
          signType: 'MD5',
          paySign: res.data.map.paySign,
          success: function (ress) {

            that.citySure();
            that.setData({
              isClick:true
            })
            wx.showModal({
              title: '温馨提示',
              content: '支付成功，感谢您的赞助！',
              confirmColor:'#ff813d',
              showCancel:'false',
              success(res) {
                if (res.confirm) {
                  that.getoneZc();
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
         
          },
          fail: function (ress) {
            that.setData({
              isClick:false
            })
            wx.showToast({
              title: "支付失败！", // 提示的内容
              icon: "none", // 图标，默认success
              duration: 3000, // 提示的延迟时间，默认1500
              mask: false, // 是否显示透明蒙层，防止触摸穿透
            })
            that.citySure();
            // that.getoneZc();
          },
          complete: function (ress) {
            //console.log("payComplete:" + JSON.stringify(res.data))
          }
        });
        // that.zhifu(res.data.dingDanHao);
      } else { //订单生成失败
        wx.showToast({
          title: "支付失败！", // 提示的内容
          icon: "none", // 图标，默认success
          duration: 2000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }
    })

  },

  //虚拟支付
  zhifu: function (dingDanHao) {
    var that = this
    that.setData({
      isClick:true
    })

    let data = {
      dingDanHao: dingDanHao,
    }
    request.get('OrderForm20231109/xiuNiZhiFu', data, res => {
      // wx.reLaunch({
      //   url: '/pkg_shop/pages/shopRaise/shopRaise?index=1',
      // })
      wx.hideLoading();
      // wx.showToast({
      //   title: '支付成功', // 提示的内容
      //   icon: "none", // 图标，默认success
      //   duration: 1500, // 提示的延迟时间，默认1500
      //   mask: false, // 是否显示透明蒙层，防止触摸穿透
      // })

   
      wx.showModal({
        title: '温馨提示',
        content: '支付成功，感谢您的赞助！',
        confirmColor:'#ff813d',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            that.getoneZc();
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
            that.setData({
              isClick:false
            })
          }

        }
      })

      that.citySure()
    })
  },

  //选择金额
  inputJe: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;

    var val = 990;
    switch (index) {
      case '1':
        val = 990;
        break;
      case '2':
        val = 1990;
        break
      case '3':
        val = 4990;
        break
      case '4':
        val = 9990;
        break
      case '5':
        val = 19990;
        break
      case '6':
        val = 29990;
        break
      case '7':
        val = 49990;
        break
      case '8':
        val = 99990;
        break
      case '9':
        val = that.data.selfLastMoney * 100;
        break
      default:

        if (e.detail.value == '' || e.detail.value == 0) {
          val = ''
        } else {
          // var inputJe = parseFloat(e.detail.value)
          // if (that.data.selfLastMoney < inputJe) {
          //   val = that.data.selfLastMoney*100
          //   index = 9;
          // } else {
          var inputJe = e.detail.value
          index = 10;
          val = inputJe.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
          val = parseInt(val * 100)

          // }
        }
    }

    this.setData({
      jinE: val,
      select_index: index,
      jinETemp: (val / 100) == 0 ? '' : (val / 100)
    })

  },

  //关闭支付弹窗
  citySure() {
    this.setData({
      visible: false,
    })
  },
  //生成众筹海报
  bindProTap: function (e) {
    wx.showLoading({
      title: '海报生成中...',
    })
    var that = this
    that.setData({
      shareble: false
    })
    that.getWechatCode(that.data.tuPianUrl);
  },

  //获取微信二维码(用于链接)
  getWechatCode: function (paperUrl) {
    var that = this
    var sceneStr = that.data.dianPuId + '_' + that.data.personId + '_' + that.data.zhongChouOrderFormId
    console.log("sceneStr：" + sceneStr)
    wx.request({
      url: app.globalData.base_url + 'resource/getQRAndUpToQiNiu',
      data: {
        id: that.data.zhongChouOrderFormId,
        dianPuId: that.data.dianPuId,
        leiXing: 3,
        path: "pages/raiseInfo/raiseInfo",
        scene: sceneStr
      },
      success: function (res) {
        console.log("wxerWeiMaUrl:" + JSON.stringify(res.data))
        var wxerWeiMaUrl = res.data.WXErWeiMaUrl;
        that.createProImg(paperUrl, wxerWeiMaUrl, that.data.myTouXiangUrl);
      }
    })
  },

  //绘制海报
  createProImg: function (paperUrl, wxerWeiMaUrl, myTouXiangUrl) {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })

    wx.hideLoading();
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {

        // console.log("画图:" + JSON.stringify(res))

        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        // console.log(renderWidth)
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        // console.log("dpr:" + dpr)
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr

        var scale = (renderWidth / 580) * dpr;

        this.setData({
          canvas: canvas,
          canvasWidth: renderWidth,
          renderHeight: renderHeight,
          canvasdestWidth: renderWidth * dpr,
          canvasdestHeight: renderHeight * dpr,
        })

        // ctx.scale(dpr, dpr)

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, 580 * scale, 920 * scale);



        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "rgb(220,220,220)"; // Green path
        ctx.moveTo(0, 660 * scale);
        ctx.lineTo(580 * scale, 660 * scale);
        ctx.stroke(); // Draw it

        //画主图      
        const imageMain = canvas.createImage();
        imageMain.src = paperUrl;
        imageMain.onload = () => {
          ctx.drawImage(imageMain, 10 * scale, 10 * scale, 560 * scale, 560 * scale)

        }



        //产品名称
        var productNameSize = 34 * scale
        var productNameSizestr = productNameSize + 'px KaiTi'

        if (this.data.chanPinMingCheng.length > 18) {
          var proName1 = this.data.chanPinMingCheng.substring(0, 18)+ '...'


          let proName1Cont = {
            x: 16 * scale,
            y: 600 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName1,
            bold: false,
            maxWidth: 540 * scale
          };
          this.drawText(ctx, proName1Cont);


          // var proName2 = this.data.chanPinMingCheng.substring(20, 40) + '...'

          // let proName2Cont = {
          //   x: 16 * scale,
          //   y: 640 * scale,
          //   color: '#474646',
          //   size: productNameSizestr,
          //   align: 'left',
          //   baseline: 'top',
          //   text: proName2,
          //   bold: false,
          //   maxWidth: 540 * scale
          // };
          // this.drawText(ctx, proName2Cont);

        // } else if (this.data.chanPinMingCheng.length < 40 && this.data.chanPinMingCheng.length > 20) {
        //   var proName1 = this.data.chanPinMingCheng.substring(0, 20)
        //   let proName1Cont = {
        //     x: 16 * scale,
        //     y: 600 * scale,
        //     color: '#474646',
        //     size: productNameSizestr,
        //     align: 'left',
        //     baseline: 'top',
        //     text: proName1,
        //     bold: false,
        //     maxWidth: 540 * scale
        //   };
        //   this.drawText(ctx, proName1Cont);

        //   var proName2 = this.data.chanPinMingCheng.substring(20, this.data.chanPinMingCheng.length)
        //   let proName2Cont = {
        //     x: 16 * scale,
        //     y: 644 * scale,
        //     color: '#474646',
        //     size: productNameSizestr,
        //     align: 'left',
        //     baseline: 'top',
        //     text: proName2,
        //     bold: false,
        //     maxWidth: 540 * scale
        //   };
        //   this.drawText(ctx, proName2Cont);

        } else {
          //画产品名称
          let chanPinMingCheng = {
            x: 16 * scale,
            y: 600 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: this.data.chanPinMingCheng,
            bold: false,
            maxWidth: 540 * scale
          };
          this.drawText(ctx, chanPinMingCheng);
        }


        //价格

        var priceIconSize = 26 * scale
        var priceIconSizestr = priceIconSize + 'px Arial'



        let raiseTxt = {
          x: 100 * scale,
          y: 706 * scale,
          color: '#474646',
          size: priceIconSizestr,
          align: 'left',
          baseline: 'top',
          text: '众筹金额：',
          bold: false,
          maxWidth: 540 * scale
        };
        this.drawText(ctx, raiseTxt);


        let shiJiJiaGeICON = {
          x: 230 * scale,
          y: 708 * scale,
          color: '#f87a41',
          size: priceIconSizestr,
          align: 'left',
          baseline: 'top',
          text: '￥',
          bold: false,
          maxWidth: 540 * scale
        };
        this.drawText(ctx, shiJiJiaGeICON);


        var priceSize = 40 * scale
        var priceSizestr = priceSize + 'px Arial'

        let shiJiJiaGe = {
          x: 260 * scale,
          y: 700 * scale,
          color: '#f87a41',
          size: priceSizestr,
          align: 'left',
          baseline: 'top',
          text: this.data.targetMoneyStr,
          bold: true,
          maxWidth: 540 * scale
        };
        this.drawText(ctx, shiJiJiaGe);


        ctx.save()
        //画二维码        
        const imageCode = canvas.createImage();
        imageCode.src = wxerWeiMaUrl;
        imageCode.onload = () => {
          ctx.drawImage(imageCode, 400 * scale, 770 * scale, 140 * scale, 140 * scale)

        }



        //画推荐人头像      
        const imageTouX = canvas.createImage();
        imageTouX.src = myTouXiangUrl;
        imageTouX.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(80 * scale, 840 * scale, 50 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(imageTouX, 30 * scale, 790 * scale, 100 * scale, 100 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制

        }

        var tjrNameSize = 28 * scale
        var tjrNameSizestr = tjrNameSize + 'px Arial'

        //推荐人昵称
        let userName = {
          x: 144 * scale,
          y: 838 * scale,
          color: '#838080',
          size: tjrNameSizestr,
          align: 'left',
          baseline: 'bottom',
          text: this.data.myName,
          bold: false,
          maxWidth: 220 * scale
        };
        this.drawText(ctx, userName);

        //推荐说明
        var tjrSMSize = 20 * scale
        var tjrSMSizestr = tjrSMSize + 'px Arial'

        let tjContent = {
          x: 144 * scale,
          y: 850 * scale,
          color: '#b3b3b3',
          size: tjrSMSizestr,
          align: 'left',
          baseline: 'top',
          text: '我在众筹，感谢您的助力',
          bold: false,
          maxWidth: 220 * scale
        };
        this.drawText(ctx, tjContent);


      })
  },

  drawText: function (ctx, obj) {
    ctx.save();
    ctx.fillStyle = obj.color;
    // ctx.setFontSize(obj.size);
    ctx.font = obj.size;
    // ctx.setTextAlign(obj.align);
    ctx.textAlign = obj.align;
    // ctx.setTextBaseline(obj.baseline);
    ctx.textBaseline = obj.baseline;

    // ctx.font="20px Georgia";
    // ctx.fillText(obj.text, obj.x,obj.y);

    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y - 0.5, obj.maxWidth);
      ctx.fillText(obj.text, obj.x - 0.5, obj.y, obj.maxWidth);
    }
    ctx.fillText(obj.text, obj.x, obj.y, obj.maxWidth);
    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y + 0.5, obj.maxWidth);
      ctx.fillText(obj.text, obj.x + 0.5, obj.y, obj.maxWidth);
    }
    ctx.restore();
  },
  //保存图片权限判断
  isgetPower: function () {

    var that = this
    wx.getSetting({
      success(res) {
        if (['scope.writePhotosAlbum'] in res.authSetting) {
          // 如果授权过且同意了
          if (res.authSetting[`scope.writePhotosAlbum`]) {
            that.bindSavePaper()
          } else {
            wx.showModal({
              title: "请求授权相册存储",
              content: "需要获取您的相册存储权限，请确认授权",
              success: res => {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                      that.bindSavePaper()
                      console.log(res)
                    },
                    fail: err => {
                      console.log(err)
                    }
                  })
                } else if (res.cancel) {
                  console.log("你又取消了")
                }
              }
            })
          }
        } else {
          that.bindSavePaper()
        }
      }
    })




  },

  //保存图片到相册
  bindSavePaper: function () {
    wx.showLoading({
      title: '保存中...',
    })

    // var that = this

    wx.canvasToTempFilePath({
      canvas: this.data.canvas,
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      destWidth: this.data.canvasdestWidth,
      destHeight: this.data.canvasdestHeight,
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            // console.log(this.saveTempFilePath)
            wx.showModal({
              title: "保存成功！",
              content: "图片已保存到本地相册",
              showCancel: false,
              success(res) {

              }
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  // 助力详情跳转
  zlxqtap: function () {
    if (this.data.personId == this.data.myPersonId && this.data.personId>0) {
      wx.navigateTo({
        url: '/pages/zlxq/zlxq?zhongChouOrderFormId=' + this.data.zhongChouOrderFormId,
      })
    }
  },

  bindClosePaper: function () {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })
  },

  //V3.0 获取手机号码
  getPhoneNumber: function (e) {
    var that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") { //允许
      that.decryptPhone(e);
    } else { //拒绝
      wx.showToast({
        title: "请授权！！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


  //V3.0 解密手机号码
  decryptPhone: function (e) {

    wx.showLoading({
      title: '解析中...',
      mask: true
    })
    var that = this;
    let code = that.data.code;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;
    wx.request({
      url: app.globalData.base_url + 'resource/getWXPhoneDirect',
      data: {
        iv: iv,
        js_code: code,
        encrypted: encryptedData,
        tuiJianRenId: that.data.tjr_id,
        dianPuId: that.data.dianPuId
      },
      success: function (res) {
        // console.log("解密手机号码:" + JSON.stringify(res.data))

        if (res.data.purePhoneNumber == '' || res.data.status == 500) {

          wx.showToast({
            title: '解析异常，右上角重新进入小程序', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })

        } else {
          wx.setStorageSync(app.globalData.OPENID, res.data.openId)
          wx.setStorageSync(app.globalData.PERSON_ID, res.data.personId)
          wx.setStorageSync(app.globalData.TOKEN, res.data.token)
          wx.setStorageSync(app.globalData.PHONENUMBER, res.data.purePhoneNumber)
          wx.setStorageSync(app.globalData.LOGINSTATUS, true)
          wx.setStorageSync(app.globalData.NiCheng, res.data.niCheng)
          wx.setStorageSync(app.globalData.TouXiang, res.data.touXiangUrl)
          that.setData({
            personId: res.data.personId,
            IsLogin: true,
            touXiangUrl: res.data.touXiangUrl,
            niCheng: res.data.niCheng,
            visible: true,
          })

          that.syncData(res.data.token)

        }
      },
      fail: function (err) {
        that.setData({
          IsLogin: false
        })
        wx.showToast({
          title: '获取数据失败,请检查网络', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {
        wx.hideLoading();
      }
    })
  },


  //登录同步健康数据
  syncData(token){


      wx.request({
        url: app.globalData.base_url + 'qiTa/tongBuJiuZhenRenAndGouMaiChanPin',
        header: {
          'token':token,  
        },
        success: function (res) {
          console.log("同步数据成功" )
        },
        fail: function (err) {
          console.log("同步数据失败" )
        },
        complete: function (res) {
          console.log("同步数据完成" )
          
        }
      })


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    that.setData({
      shareble: false
    })
    var pathStr = '/pages/raiseInfo/raiseInfo?shareFlag=true' + '&dianPuId=' + that.data.dianPuId + '&tjr_id=' + that.data.personId + '&zhongChouOrderFormId=' + that.data.zhongChouOrderFormId
    var imgUrl = that.data.tuPianUrl
    if (that.data.IsLogin) {
      return {
        title: '众筹活动',
        path: pathStr,
        imageUrl: imgUrl
      }
    } else {
      that.toLogin();
    }
  }
})